<?php
/**
 * common repository file Created by PhpStorm.
 * User: yang
 * Date: 2020/04/28
 */

namespace Common\Repository;

use Common\Model\Power;
use Common\Model\AdminRoles;

class PowerRepository extends BaseRepository
{
    public function baseModel()
    {
        return new Power();
    }

    /**
     * @param $admin_id
     * @return array
     */
    public function extendGetAll($admin_id)
    {
        $model = new Power();
        if ($admin_id != 1) {
            //获取管理员所属的角色
            $roles = AdminRoles::where('admin_id', $admin_id)->with(['get_power'])
                ->whereHas('roles')->select('roles_id')->get()->toArray();
            if ($roles) {
                $powers = [];
                foreach ($roles as $item) {
                    $power = array_column($item['get_power'], 'power_id');
                    $powers = array_merge($powers, $power);
                }
                $model = $model->whereIn('id', array_unique($powers));
            }else{
                return [];
            }

        }
        return $model->select(['id', 'pid', 'name', 'route', 'alias', 'ico'])
            ->where('type', 1)->orderBy('sort', 'asc')->get()->toArray();
    }

    /**
     * @param $admin_id
     * @return array
     */
    public function getPower($admin_id)
    {
        $model = new Power();
        if ($admin_id != 1) {
            //获取管理员所属的角色
            $roles = AdminRoles::where('admin_id', $admin_id)->with(['get_power'])
                ->whereHas('roles')->select('roles_id')->get()->toArray();
            if ($roles) {
                $powers = [];
                foreach ($roles as $item) {
                    $power = array_column($item['get_power'], 'power_id');
                    $powers = array_merge($powers, $power);
                }
                $model = $model->whereIn('id', array_unique($powers));
            }
        }
        return $model->select(['id','alias'])
            ->where('type', 2)->orderBy('sort', 'asc')->get()->toArray();
    }
}